//
//  LoginViewController.m
//  sellHouse
//
//  Created by 李 佳伟 on 2018/11/20.
//  Copyright © 2018年 李 佳伟. All rights reserved.
//

#import "LoginViewController.h"
#import "InputView.h"
#import "JTCSM.h"


@interface LoginViewController ()<UITextFieldDelegate>
{
    InputView *_phoneView;
    InputView *_codeVoiew;
    NSTimer *_timer;
    int _waiTime;
    
}
@property (nonatomic,strong) UILabel *lgoinView;
@property (nonatomic,strong) NSString *phone;
@property (nonatomic,strong) NSString *code;
@end

@implementation LoginViewController

- (void)gotoback{
    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"gotomyPageVC" object:self];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarHidden:NO withAnimation:NO];
    [df isRemoveTarbar:YES];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.phone = @"";
    self.code = @"";
    KUSERDEFAULTRemoveAll(KuserInfo);
    KUSERDEFAULTRemoveAll(Khtml_user);
    // Do any additional setup after loading the view.
    
    CGRect rect = [df labelHeightWithContent:@"测试数据五" width:200 font:20];
    UILabel *headertitleLabel = [UILabel initWithFrame:CGRectMake(0, 0, rect.size.width, 40) text:@"登录" font:20 textAlignment:NSTextAlignmentCenter texcolor:[UIColor whiteColor] backgroundColor:[UIColor clearColor]];
    [self.navigationItem setTitleView:headertitleLabel];
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.barTintColor = [df colorWithHexString:@"0fa6e8" alpha:1];
    leftBarButtonItems_rightBarButtonItems *leftbtn = KCUSTOMNAVIGSTION_ALLOC;
    self.navigationItem.leftBarButtonItem= [leftbtn setBarButtonItemsImageName:@"erweimafanhui.png" frame:KLeftBarButtonItemFrame_image target:self SEL:@selector(gotoback)];
    
    UIImageView *logo = [[UIImageView alloc]initWithFrame:CGRectMake(Kspace-2, Height_NavBar+KAutoSize(27), 109*KSCREENWidth/375, 33*KSCREENWidth/375)];
    logo.image = [UIImage imageNamed:@"sellhouse.jpg"];
    [self.view addSubview:logo];
    
    
    UILabel *titleLabel = [UILabel initWithFrame:CGRectMake(Kspace,KVIEW_Y(logo)+KAutoSize(20), KSCREENWidth-2*Kspace, 30) text:@"欢迎你" font:23 textAlignment:NSTextAlignmentLeft texcolor:RGBACOLOR(37, 37, 37, 1) backgroundColor:nil];
    [titleLabel setFont:[UIFont fontWithName:@"Helvetica-Bold" size:23]];
    [self.view addSubview:titleLabel];
    
    CGFloat inputviewheight = 43;
    _phoneView = [[InputView alloc]initWithFrame:CGRectMake(Kspace, KVIEW_Y(titleLabel)+KAutoSize(20), KSCREENWidth-2*Kspace, inputviewheight) placeholder:@"请输入手机号" isshow_touch:NO];
    [self.view addSubview:_phoneView];
    _phoneView.textfield.delegate = self;
    _phoneView.textfield.keyboardType = UIKeyboardTypeNumberPad;
    [_phoneView.textfield addTarget:self action:@selector(textField1TextChange:) forControlEvents:UIControlEventEditingChanged];
    
    _codeVoiew = [[InputView alloc]initWithFrame:CGRectMake(Kspace, KVIEW_Y(_phoneView)+10, KSCREENWidth-2*Kspace, inputviewheight) placeholder:@"请输入验证码" isshow_touch:YES];
    [self.view addSubview:_codeVoiew];
    [df addTapGestureRecognizerWithTarget:self action:@selector(getcode) andaddView:_codeVoiew.touchview];
    _codeVoiew.textfield.delegate = self;
    _codeVoiew.textfield.keyboardType = UIKeyboardTypeNumberPad; 
     [_codeVoiew.textfield addTarget:self action:@selector(textField1TextChange:) forControlEvents:UIControlEventEditingChanged];
    
    _lgoinView = [UILabel initWithFrame:CGRectMake(Kspace+10, KVIEW_Y(_codeVoiew)+24, KSCREENWidth-2*Kspace-20, 44) text:@"登录" font:16 textAlignment:NSTextAlignmentCenter texcolor:[UIColor whiteColor] backgroundColor:RGBACOLOR(15,166,232,1)];
    [df layerWithView:_lgoinView radius:4 width:0 color:nil];
    [self.view addSubview:_lgoinView];
    _lgoinView.userInteractionEnabled = YES;
    self.view.userInteractionEnabled = YES;
    [df addTapGestureRecognizerWithTarget:self action:@selector(gotoMainVC) andaddView:_lgoinView];
    
    UILabel *title1= [ UILabel initWithFrame:CGRectMake(0, KVIEW_Y(_lgoinView)+KAutoSize(8), KSCREENWidth, 20) text:@"无需注册,直接登录" font:15 textAlignment:NSTextAlignmentCenter texcolor:RGBACOLOR(151, 151, 151, 1) backgroundColor:nil];
    [self.view addSubview:title1];
    
    
    NSString *title = @"登录即代表同意 《秒卖房用户使用协议》";
    UILabel *title2= [ UILabel initWithFrame:CGRectMake(0, KVIEW_Y(title1)+KAutoSize(10), KSCREENWidth, 20) text:title font:15 textAlignment:NSTextAlignmentCenter texcolor:RGBACOLOR(151, 151, 151, 1) backgroundColor:nil];
    [df fuwenbenLabel:title2 FontNumber:[UIFont systemFontOfSize:15] AndRange:NSMakeRange(title.length-11, 11) AndColor:RGBACOLOR(1, 84, 182, 1)];
    [self.view addSubview:title2];
    title2.userInteractionEnabled = YES;
    [df addTapGestureRecognizerWithTarget:self action:@selector(gotoweb) andaddView:title2];
    
}
- (void)gotoweb{
    WebViewController *vc = [[WebViewController alloc]init];
    vc.urlStr = KWEBURLHEADER(@"xieyi.html");
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)textField1TextChange:(UITextField *)textfield{
    if (textfield == _phoneView.textfield) {
        self.phone = textfield.text;
    }
    if (textfield == _codeVoiew.textfield) {
        self.code = textfield.text;
    }
}

#pragma mark 手机号

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string

{
    
    if (textField == _phoneView.textfield) {
        
        if (string.length == 0) {return YES;}
        
        NSInteger existedLength = textField.text.length;
        
        NSInteger selectedLength = range.length;
        
        NSInteger replaceLength = string.length;
        
        if (existedLength - selectedLength + replaceLength > 11) {
            
            return NO;
            
        }
        
    }
    
    
    
    return YES;//YES，表示修改生效；NO，表示不做修改，textField的内容不变
    
    
    
    
    
}

- (void)textFieldDidChange:(UITextField *)textField

{
    
    if (textField == _phoneView.textfield) {
        
        if (textField.text.length > 11) {
            
            textField.text = [textField.text substringToIndex:11];
            
        }
        
    }
    
}


- (BOOL)isPhone_number:(NSString *)phonenumber{
    NSString *MOBILE = @"^1(3[0-9]|4[57]|5[0-35-9]|8[0-9]|7[0678])\\d{8}$";
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    return [regextestmobile evaluateWithObject:phonenumber];
}

-(void)gotoMainVC{
    
    
    
    if (_phone==nil || [_phone isEqualToString:@""]) {
        [df showAlertWithTitle:@"手机号不能为空" message:nil btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
        return;
    }
    if (![self isPhone_number:_phone]) {
        [df showAlertWithTitle:@"手机号不正确" message:nil btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
        return;
    }
    
    if (_code==nil || [_code isEqualToString:@""]) {
        [df showAlertWithTitle:@"验证码不能为空" message:nil btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
        return;
    }

    [[LoadData object] loadDataPostAsynchronousWithURL:@"app/mobile/applogin" withDict:@{@"phone":_phone,@"code":_code} superView:self.view Block:^(id  _Nullable responseObject) {
        if([[responseObject allKeys] containsObject:@"data"]){
            KUSERDEFAULTSET([responseObject objectForKey:@"data"], KuserInfo);
            KUSERDEFAULTSET(responseObject, Khtml_user);
            [self.delegate gotoMainViewController];
        }else{
            [df showAlertWithTitle:@"验证码错误" message:nil btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
        }
        
    }];
    
}


#pragma mark 获取验证码
- (void)getcode{
    NSLog(@"%@",_phone);
    if ([df isValidMobile:self.phone]) {
        [self startTime];
        NSNumber *phone = [[NSNumber alloc]initWithInteger:[self.phone integerValue]];
        [[LoadData object] loadDataPostAsynchronousWithURL:@"sms/appcode" withDict:@{@"phone":phone} superView:self.view Block:^(id  _Nullable responseObject) {
            
        }];
        
    }else{
        [df showAlertWithTitle:@"手机号不正确" message:@"" btn1:@"知道了" btn2:nil btn3:nil delegate:nil tag:0];
    }
    
}

#pragma mark--开始计时
- (void)startTime {
    
    [_timer invalidate];
    _waiTime = 60;
    [self updateVareyButton];
    _timer = [NSTimer scheduledTimerWithTimeInterval:1.0
                                              target:self
                                            selector:@selector(updateWaitTime)
                                            userInfo:nil
                                             repeats:YES];
}

- (void)updateVareyButton {
    
    NSString *title = @"获取验证码";
    if (_waiTime > 0) {
        title = [NSString stringWithFormat:@"%d秒后重发", _waiTime];
        _codeVoiew.touchview.userInteractionEnabled = NO;
    }
    _codeVoiew.touchview.text =title;
}

- (void)updateWaitTime {
    
    _waiTime = _waiTime - 1;
    [self updateVareyButton];
    if (_waiTime <= 0) {
        _codeVoiew.touchview.userInteractionEnabled = YES;
        [_timer invalidate];
        _timer = nil;
    }
    
}
@end
